<template>
    <div class="admin-approve-container">
        <div class="filter-container">
            <el-form :inline="true" :model="listQuery" class="demo-form-inline">
                <el-form-item label="成果类型">
                    <el-select v-model="listQuery.achievementType" placeholder="请选择成果类型" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="论文" :value="1" />
                        <el-option label="专利" :value="2" />
                        <el-option label="竞赛证书" :value="3" />
                        <el-option label="项目计划" :value="4" />
                        <el-option label="其他" :value="5" />
                    </el-select>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-select v-model="listQuery.status" placeholder="请选择审核状态" clearable style="width: 150px">
                        <el-option label="全部" value="" />
                        <el-option label="初审通过" :value="1" />
                        <el-option label="终审通过" :value="3" />
                        <el-option label="终审拒绝" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学生姓名">
                    <el-input v-model="listQuery.studentName" placeholder="请输入学生姓名" style="width: 150px;"
                        @keyup.enter.native="handleFilter" />
                </el-form-item>
                <el-form-item label="初审教师">
                    <el-input v-model="listQuery.teacherName" placeholder="请输入教师姓名" style="width: 150px;"
                        @keyup.enter.native="handleFilter" />
                </el-form-item>
                <el-form-item label="关键词">
                    <el-input v-model="listQuery.keyword" placeholder="请输入成果标题" style="width: 200px;"
                        @keyup.enter.native="handleFilter" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleFilter">
                        搜索
                    </el-button>
                    <el-button icon="el-icon-refresh" @click="handleReset">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
            style="width: 100%">
            <el-table-column align="center" label="ID" width="80">
                <template slot-scope="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column label="学生信息" width="150" align="center">
                <template slot-scope="scope">
                    <div>
                        <div>{{ scope.row.studentName }}</div>
                        <div class="text-muted" style="font-size: 12px;">{{ scope.row.account }}</div>
                        <div class="text-muted" style="font-size: 12px;">{{ scope.row.department }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="成果标题" min-width="200" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span class="title-text" @click="handleView(scope.row)">{{ scope.row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="成果类型" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getTypeTagType(scope.row.achievementType)">
                        {{ getTypeLabel(scope.row.achievementType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="级别" width="100" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.level" size="small" :type="getLevelTagType(scope.row.level)">
                        {{ getLevelLabel(scope.row.level) }}
                    </el-tag>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="初审教师" width="120" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.teacherName">{{ scope.row.teacherName }}</span>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="审核状态" width="120" align="center">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">
                        {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="提交时间" width="160" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" />
                    <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="附件" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-dropdown v-if="scope.row.attachments && scope.row.attachments.length > 0" trigger="click">
                        <el-button type="text" size="small" class="attachment-btn">
                            附件下载 <i class="el-icon-arrow-down el-icon--right" />
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="(file, index) in scope.row.attachments" :key="index"
                                class="attachment-item" @click.native="handleDownloadAttachment(file)">
                                <i :class="getFileIcon(file.fileType)" class="file-icon" />
                                <span class="file-name">{{ file.name }}</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span v-else class="text-muted">-</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleView(scope.row)">
                        查看详情
                    </el-button>
                    <el-button v-if="scope.row.status === 1" type="success" size="mini"
                        @click="handleApprove(scope.row)">
                        终审通过
                    </el-button>
                    <el-button v-if="scope.row.status === 1" type="danger" size="mini" @click="handleReject(scope.row)">
                        终审拒绝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
            @pagination="getList" />

        <!-- 终审对话框 -->
        <el-dialog :title="approvalDialogTitle" :visible.sync="approvalDialogVisible" width="600px"
            @close="resetApprovalForm">
            <el-form ref="approvalForm" :model="approvalForm" :rules="approvalRules" label-width="100px">
                <el-form-item label="审核结果">
                    <el-tag :type="approvalForm.status === 1 ? 'success' : 'danger'">
                        {{ approvalForm.status === 1 ? '通过' : '拒绝' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="审核意见" prop="comment">
                    <el-input v-model="approvalForm.comment" type="textarea" :rows="4"
                        :placeholder="approvalForm.status === 1 ? '请输入通过理由（可选）' : '请输入拒绝理由'" maxlength="500"
                        show-word-limit />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="approvalDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmApproval" :loading="approvalLoading">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getAdminApprovalList, adminApproval } from '@/api/achievement'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
    name: 'AdminApprove',
    components: { Pagination },
    filters: {
        parseTime(time, pattern) {
            return parseTime(time, pattern)
        }
    },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: true,
            listQuery: {
                pageNo: 1,
                pageSize: 20,
                achievementType: '',
                status: '',
                studentName: '',
                teacherName: '',
                keyword: ''
            },
            approvalDialogVisible: false,
            approvalDialogTitle: '',
            approvalLoading: false,
            currentRow: null,
            approvalForm: {
                id: '',
                status: 1, // 1-通过, 2-拒绝
                comment: ''
            },
            approvalRules: {
                comment: [
                    { validator: this.validateApprovalComment, trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            this.listLoading = true
            try {
                const res = await getAdminApprovalList(this.listQuery)
                this.list = res.data.records || [];
                this.total = res.data.total || 0;
                this.list.forEach(item => {
                    // 解析附件URL
                    if (item.fileUrl) {
                        try {
                            item.attachments = JSON.parse(item.fileUrl)
                        } catch (e) {
                            item.attachments = []
                        }
                    } else {
                        item.attachments = []
                    }
                })
            } catch (error) {
                console.error('获取待审批成果列表失败:', error)
            } finally {
                this.listLoading = false
            }
            // 模拟数据
            /*
            setTimeout(() => {
                const mockData = {
                    records: [
                        {
                            id: 1,
                            title: '基于区块链的供应链管理系统研究',
                            achievementType: 1,
                            tags: '国家级',
                            courseName: '区块链技术',
                            semester: '2024-2025-1',
                            status: 1,
                            studentName: '陈七',
                            studentNumber: '2021001005',
                            department: '计算机科学与技术学院',
                            major: '计算机科学与技术',
                            teacherName: '张教授',
                            createTime: '2024-10-10 08:30:00',
                            teacherReviewTime: '2024-10-15 14:20:00',
                            teacherReviewComment: '该论文研究内容新颖，技术方案可行，建议通过初审。',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '论文全文.pdf',
                                    url: 'https://example.com/blockchain_paper.pdf',
                                    fileType: 'pdf',
                                    size: 4194304
                                },
                                {
                                    name: '系统演示视频.mp4',
                                    url: 'https://example.com/demo.mp4',
                                    fileType: 'mp4',
                                    size: 52428800
                                }
                            ])
                        },
                        {
                            id: 2,
                            title: '新型环保材料发明专利',
                            achievementType: 2,
                            tags: '省级',
                            courseName: '材料科学基础',
                            semester: '2024-2025-1',
                            status: 1,
                            studentName: '刘八',
                            studentNumber: '2021002001',
                            department: '材料科学与工程学院',
                            major: '材料科学与工程',
                            teacherName: '李教授',
                            createTime: '2024-10-08 16:45:00',
                            teacherReviewTime: '2024-10-12 10:30:00',
                            teacherReviewComment: '专利申请材料完整，技术创新性强，符合申报要求。',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '专利申请书.pdf',
                                    url: 'https://example.com/material_patent.pdf',
                                    fileType: 'pdf',
                                    size: 3145728
                                },
                                {
                                    name: '实验报告.docx',
                                    url: 'https://example.com/experiment_report.docx',
                                    fileType: 'docx',
                                    size: 2097152
                                }
                            ])
                        },
                        {
                            id: 3,
                            title: '全国电子设计竞赛特等奖',
                            achievementType: 3,
                            tags: '国家级',
                            courseName: '电子电路设计',
                            semester: '2023-2024-2',
                            status: 3,
                            studentName: '周九',
                            studentNumber: '2021003001',
                            department: '电子信息工程学院',
                            major: '电子信息工程',
                            teacherName: '王教授',
                            createTime: '2024-09-25 13:20:00',
                            teacherReviewTime: '2024-09-28 09:15:00',
                            teacherReviewComment: '该同学在电子设计竞赛中获得特等奖，成绩优异。',
                            adminReviewTime: '2024-10-05 15:45:00',
                            adminReviewComment: '经终审，该成果达到国家级水平，予以通过并给予优秀等级。',
                            achievementLevel: '优秀',
                            rewardPoints: 50,
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '获奖证书.jpg',
                                    url: 'https://example.com/electronics_certificate.jpg',
                                    fileType: 'jpg',
                                    size: 2097152
                                },
                                {
                                    name: '作品说明书.pdf',
                                    url: 'https://example.com/work_description.pdf',
                                    fileType: 'pdf',
                                    size: 1572864
                                }
                            ])
                        },
                        {
                            id: 4,
                            title: '智慧城市交通优化算法设计',
                            achievementType: 4,
                            tags: '省级',
                            courseName: '算法设计',
                            semester: '2024-2025-1',
                            status: 4,
                            studentName: '吴十',
                            studentNumber: '2021001006',
                            department: '计算机科学与技术学院',
                            major: '软件工程',
                            teacherName: '赵教授',
                            createTime: '2024-09-20 10:00:00',
                            teacherReviewTime: '2024-09-25 14:30:00',
                            teacherReviewComment: '算法设计思路清晰，但实验验证不够充分。',
                            adminReviewTime: '2024-10-02 11:20:00',
                            adminReviewComment: '经终审，该项目在理论创新方面有所欠缺，实用性有待提高，不予通过。',
                            attachmentUrl: JSON.stringify([
                                {
                                    name: '算法设计文档.pdf',
                                    url: 'https://example.com/algorithm_design.pdf',
                                    fileType: 'pdf',
                                    size: 2621440
                                }
                            ])
                        }
                    ],
                    total: 4
                }

                // 解析附件URL
                this.list = mockData.records.map(item => {
                    if (item.attachmentUrl) {
                        try {
                            item.attachments = JSON.parse(item.attachmentUrl)
                        } catch (e) {
                            item.attachments = []
                        }
                    } else {
                        item.attachments = []
                    }
                    return item
                })
                this.total = mockData.total
                this.listLoading = false
            }, 1000) */
        },
        handleFilter() {
            this.listQuery.pageNo = 1
            this.getList()
        },
        handleReset() {
            this.listQuery = {
                pageNo: 1,
                pageSize: 20,
                achievementType: '',
                status: '',
                studentName: '',
                teacherName: '',
                keyword: ''
            }
            this.getList()
        },
        handleView(row) {
            this.$router.push(`/achievement/detail/${row.id}`)
        },
        handleApprove(row) {
            this.currentRow = row
            this.approvalForm.id = row.id
            this.approvalForm.status = 1
            this.approvalForm.comment = ''
            this.approvalDialogTitle = '终审通过'
            this.approvalDialogVisible = true
        },
        handleReject(row) {
            this.currentRow = row
            this.approvalForm.id = row.id
            this.approvalForm.status = 2
            this.approvalForm.comment = ''
            this.approvalDialogTitle = '终审拒绝'
            this.approvalDialogVisible = true
        },
        confirmApproval() {
            this.$refs.approvalForm.validate((valid) => {
                if (valid) {
                    this.approvalLoading = true
                    adminApproval(this.approvalForm).then(() => {
                        this.$message.success('终审完成!')
                        this.approvalDialogVisible = false
                        this.getList()
                    }).catch(() => {
                        this.$message.error('终审失败')
                    }).finally(() => {
                        this.approvalLoading = false
                    })
                }
            })
        },
        resetApprovalForm() {
            this.approvalForm = {
                id: '',
                status: 1,
                comment: ''
            }
            this.currentRow = null
            if (this.$refs.approvalForm) {
                this.$refs.approvalForm.resetFields()
            }
        },
        validateApprovalComment(rule, value, callback) {
            if (this.approvalForm.status === 2 && (!value || value.trim() === '')) {
                callback(new Error('终审拒绝时必须填写拒绝理由'))
            } else {
                callback()
            }
        },
        handleDownloadAttachment(file) {
            window.open(file.url, '_blank')
        },
        getTypeLabel(type) {
            const typeMap = {
                1: '论文',
                2: '专利',
                3: '竞赛证书',
                4: '项目计划',
                5: '其他'
            }
            return typeMap[type] || '未知'
        },
        getTypeTagType(type) {
            const typeMap = {
                1: 'primary',
                2: 'success',
                3: 'warning',
                4: 'info',
                5: 'danger'
            }
            return typeMap[type] || ''
        },
        getStatusLabel(status) {
            const statusMap = {
                1: '初审通过',
                3: '终审通过',
                4: '终审拒绝'
            }
            return statusMap[status] || '未知'
        },
        getStatusTagType(status) {
            const statusMap = {
                1: 'warning',
                3: 'success',
                4: 'danger'
            }
            return statusMap[status] || ''
        },
        getLevelLabel(level) {
            const levelMap = {
                1: '国家级',
                2: '省级',
                3: '市级',
                4: '校级'
            }
            return levelMap[level] || '未知'
        },
        getLevelTagType(level) {
            const levelMap = {
                1: 'danger',   // 国家级 - 红色
                2: 'warning',  // 省级 - 橙色
                3: 'primary',  // 市级 - 蓝色
                4: 'success'   // 校级 - 绿色
            }
            return levelMap[level] || 'info'
        },
        getFileIcon(fileType) {
            const iconMap = {
                'pdf': 'el-icon-document',
                'doc': 'el-icon-document',
                'docx': 'el-icon-document',
                'jpg': 'el-icon-picture',
                'jpeg': 'el-icon-picture',
                'png': 'el-icon-picture',
                'gif': 'el-icon-picture'
            }
            return iconMap[fileType] || 'el-icon-document'
        }
    }
}
</script>

<style lang="scss" scoped>
.admin-approve-container {
    padding: 20px;
}

.filter-container {
    padding-bottom: 20px;
}

.title-text {
    cursor: pointer;
    color: #409EFF;

    &:hover {
        text-decoration: underline;
    }
}

.text-muted {
    color: #999;
}

.attachment-btn {
    padding: 0;
    font-size: 12px;
}

.attachment-item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    cursor: pointer;

    &:hover {
        background-color: #f5f7fa;
    }
}

.file-icon {
    margin-right: 8px;
    color: #409EFF;
}

.file-name {
    font-size: 12px;
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>